package com.general.app.xtgl.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.general.common.action.BaseAction;
import com.general.common.security.entity.User;
import com.general.utils.base.Constant;
import com.general.utils.base.IPRequest;
import com.general.utils.base.StringUtil;
import com.general.utils.encrypt.Encrypt;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 登录认证模块
 * 
 * @author Penghui.Qu
 * 
 */

public class LoginAction extends BaseAction implements ModelDriven<User> {

	private static final long serialVersionUID = -1110264619149651296L;
	private Logger log = LoggerFactory.getLogger(LoginAction.class);

    public static final String INDEX_ANSWER = "indexAnswer";
    public static final String SUCCESS_PHONE = "successPhone";
	private User user = new User();

	//SecurityUtils.getSubject().getPrincipal(); 取User对象
	
	//@RequiresPermissions("user:edit")
	//@RequiresRoles(value = { "Admin", "User" }, logical = Logical.OR)
	//验证码session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY)
	
	
	/**
	 * 登录认证
	 * 
	 * @return
	 */
	public String login() {

		//构建当前操作用户
		//WebSubject.Builder b = new WebSubject.Builder(request, response);
		//Subject subject = b.buildSubject();
		Subject subject = SecurityUtils.getSubject();
		
		// 判断当前用户是否认证过
		if (subject.isAuthenticated()) {
			HttpSession session = getSession();
			String usertype  = (String)session.getAttribute("userType");
			
			ValueStack vs = getValueStack();	
			vs.set("userType", usertype);		
			User user = getCurrentUser();
			vs.set("username", user.getUsername());

			// =============================手机端START====================================
			// 判断是否是手机端（true:手机端）/false:PC端）
			boolean isMobileDevice = HttpRequestDeviceUtils.isMobileDevice(getRequest());
			if(!StringUtil.isEmpty(usertype) && Constant.USER_TYPE_ANSWER.equals(usertype) 
					&& isMobileDevice){
				return SUCCESS_PHONE;
			}
			// =============================手机端END======================================
			
			//问卷回答者则跳转到答卷面页
			if(Constant.USER_TYPE_ANSWER.equals(usertype)){
				return INDEX_ANSWER;
			}
			return SUCCESS;
		}
			
		// 答卷者
		if (!StringUtil.isEmpty(user.getType())
				&& Constant.USER_TYPE_ANSWER.equals(user.getType())
				&& !StringUtil.isEmpty(user.getUsername())) {

				UsernamePasswordToken token = new UsernamePasswordToken(
						user.getUsername(), Encrypt.encrypt("0"));
				try {
					
					//登录认证
					subject.login(token);
					HttpSession session = getSession();
					session.setAttribute("userType", Constant.USER_TYPE_ANSWER);			
					ValueStack vs = getValueStack();		
					vs.set("usertype", Constant.USER_TYPE_ANSWER);
					User user = getCurrentUser();
					vs.set("username", user.getUsername());
					//登录认证
					token.setRememberMe(true);
					
					// =============================手机端START====================================
					// 判断是否是手机端（true:手机端）/false:PC端）
					boolean isMobileDevice = HttpRequestDeviceUtils.isMobileDevice(getRequest());
					if(isMobileDevice){
						return SUCCESS_PHONE;
					}
					// =============================手机端END======================================
					return INDEX_ANSWER;
				} catch (Exception e) {

					//认证失败
					String errMsg = null;
					
					if (e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException) {
						errMsg = "IP:{},UserName:{},认证失败！";
					} else {
						errMsg = "IP:{},UserName:{},登录异常！";
					}

					HttpServletRequest request = getRequest();
					String ip = IPRequest.getIpAddress(request);
					
					if (log.isDebugEnabled()){
						log.debug(errMsg,ip,user.getUsername());
					}
					token.clear();					
					getValueStack().set("message", "登陆失败！");
				}
			}
			
			//用户名或密码为空
			if (StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getUsername())){
				
				return LOGIN;
			}
		
			UsernamePasswordToken token = new UsernamePasswordToken(
					user.getUsername(), Encrypt.encrypt(user.getPassword()));
		try {
				//登录认证
				token.setRememberMe(true);
				subject.login(token);
	
				HttpSession session = getSession();
				session.setAttribute("userType", Constant.USER_TYPE_MANAGER);
				ValueStack vs = getValueStack();		
				vs.set("userType", Constant.USER_TYPE_MANAGER);
				User user = getCurrentUser();
				vs.set("username", user.getUsername());
				return SUCCESS;
			
		} catch (Exception e) {

			//认证失败
			String errMsg = null;
			
			if (e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException) {
				errMsg = "IP:{},UserName:{},认证失败！";
			} else {
				errMsg = "IP:{},UserName:{},登录异常！";
			}

			HttpServletRequest request = getRequest();
			String ip = IPRequest.getIpAddress(request);
			
			if (log.isDebugEnabled()){
				log.debug(errMsg,ip,user.getUsername());
			}
			token.clear();
			
			getValueStack().set("message", "用户名或密码错误，请重新输入。");
		}
		return LOGIN;
	}


	/**
	 * 登录认证[答卷者]
	 * 
	 * @return
	 */
	public String loginAnswer() {

		//构建当前操作用户
		Subject subject = SecurityUtils.getSubject();
		
		// 判断当前用户是否认证过
		if (subject.isAuthenticated()) {
			return SUCCESS;
		}
		
		//用户名或密码为空
		if (StringUtil.isEmpty(user.getUsername())){
			return LOGIN;
		}

		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getUsername(), Encrypt.encrypt("0"));
		try {
			//登录认证
			//token.setRememberMe(true);
			subject.login(token);
			
			return "successAnswer";
		} catch (Exception e) {

			//认证失败
			String errMsg = null;
			
			if (e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException) {
				errMsg = "IP:{},UserName:{},认证失败！";
			} else {
				errMsg = "IP:{},UserName:{},登录异常！";
			}

			HttpServletRequest request = getRequest();
			String ip = IPRequest.getIpAddress(request);
			
			if (log.isDebugEnabled()){
				log.debug(errMsg,ip,user.getUsername());
			}
			token.clear();
			e.printStackTrace();
		}
		return LOGIN;
	}
	
	/**
	 * 注销
	 * @return
	 */
	public String logout(){
		
		Subject subject = SecurityUtils.getSubject();
		
		subject.logout();
		
		return LOGIN;
	}

	/**
	 * 跳转首页
	 * @return 首页
	 */
	public String indexBody(){
		
		return "indexBody";
	}
	
	@Override
	public User getModel() {
		
		return user;
	}
}
